package com.zksite.nator.server.http.initialzer;

import org.springframework.stereotype.Component;

import com.zksite.nator.common.context.SpringApplicationContext;
import com.zksite.nator.server.http.handler.HttpServerHandler;
import com.zksite.nator.server.http.ssl.SslContextFactory;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.ssl.SslHandler;

@Component
public class HttpServerInitializer extends ChannelInitializer<Channel> {

	@Override
	protected void initChannel(Channel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();

		SslHandler sslHandler = SslContextFactory.getSslContext().newHandler(ch.alloc());
		if (sslHandler != null) {
			// pipeline.addFirst(sslHandler);
		}
		pipeline.addLast("http-decoder", new HttpRequestDecoder());
		pipeline.addLast("http-encoder", new HttpResponseEncoder());
		pipeline.addLast("httpObject", new HttpObjectAggregator(Integer.MAX_VALUE));
		HttpServerHandler httpServerHandler = SpringApplicationContext.getBean(HttpServerHandler.class);
		pipeline.addLast(httpServerHandler);
	}

}
